package xyz.zhzby.cyzx.security.util;

import org.springframework.security.core.context.SecurityContextHolder;
import xyz.zhzby.cyzx.security.entity.User;
import xyz.zhzby.cyzx.servicebase.exception.CommonErrorMessageEnum;

/**
 * @author zby
 * @date 2021/12/08
 */
public class CyzxSecurityContextHolder {

    public static User getSubject() {
        if (SecurityContextHolder.getContext() == null
                || SecurityContextHolder.getContext().getAuthentication() == null
                || SecurityContextHolder.getContext().getAuthentication().getPrincipal() == null) {

            throw CommonErrorMessageEnum.NO_LOGIN.businessException();
        }
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof User) {
            return (User) principal;
        } else {
            throw CommonErrorMessageEnum.NO_LOGIN.businessException();
        }
    }


}
